----------------------------------------------------------------------------------------------------------------------------------------------------
--[[

    乾坤帽 容器模块

]]--
----------------------------------------------------------------------------------------------------------------------------------------------------
---- 
    local SLOT_OFFSET_Y = -40
----------------------------------------------------------------------------------------------------------------------------------------------------
---- 可放入物品
    local item_logic_data = require("prefabs/06_equipments/05_03_cosmic_hat_item_logic").item_logic
    local function itemCheck(item)
        return item_logic_data[item.prefab] ~= nil
    end
----------------------------------------------------------------------------------------------------------------------------------------------------
---- hook container 
    local function conainter_IsRestricted(conainer_com, target)
        if not target:HasTag("player") then
            return true
        end
        if conainer_com.inst.components.hutao_com_cosmic_hat_sys_for_item then
           return not conainer_com.inst.components.hutao_com_cosmic_hat_sys_for_item:IsLinkingPlayer(target)
        end
        return true
    end
    local function hook_container(inst)
       inst.components.container.IsRestricted =  conainter_IsRestricted
    end
----------------------------------------------------------------------------------------------------------------------------------------------------
---- 安装容器界面
    local function container_Widget_change(theContainer)
        -----------------------------------------------------------------------------------
        ----- 容器界面名 --- 要独特一点，避免冲突
        local container_widget_name = "hutao_equipment_cosmic_hat_sky"

        -----------------------------------------------------------------------------------
        ----- 检查和注册新的容器界面
        local all_container_widgets = require("containers")
        local params = all_container_widgets.params
        if params[container_widget_name] == nil then
            params[container_widget_name] = {
                widget =
                {
                    slotpos =
                    {
                        Vector3(0, 64 + 32 + 8 + 4 + SLOT_OFFSET_Y, 0),
                        Vector3(0, 32 + 4 + SLOT_OFFSET_Y, 0),
                        Vector3(0, -(32 + 4) + SLOT_OFFSET_Y, 0),
                        Vector3(0, -(64 + 32 + 8 + 4) + SLOT_OFFSET_Y, 0),
                    },
                    animbank = "ui_cookpot_1x4",
                    animbuild = "ui_cookpot_1x4",
                    pos = Vector3(200, 0, 0),
                },
                type = "hutao_equipment_cosmic_hat_sky",
                acceptsstacks = true,
            }
            ------------------------------------------------------------------------------------------
            ---- item test
                params[container_widget_name].itemtestfn =  function(container_com, item, slot)
                    return itemCheck(item)
                end
            ------------------------------------------------------------------------------------------

            ------------------------------------------------------------------------------------------
        end
        
        theContainer:WidgetSetup(container_widget_name)
        ------------------------------------------------------------------------
        --- 开关声音
            -- if theContainer.widget then
            --     theContainer.widget.closesound = "turnoftides/common/together/water/splash/small"
            --     theContainer.widget.opensound = "turnoftides/common/together/water/splash/small"
            -- end
        ------------------------------------------------------------------------
    end
    
    local function add_container_before_not_ismastersim_return(inst)
        -------------------------------------------------------------------------------------------------
        ------ 添加背包container组件    --- 必须在 SetPristine 之后，
        -- local container_WidgetSetup = "wobysmall"
        if TheWorld.ismastersim then
            inst:AddComponent("container")
            inst.components.container.openlimit = 1  ---- 限制1个人打开
            -- inst.components.container:WidgetSetup(container_WidgetSetup)
            container_Widget_change(inst.components.container)
            hook_container(inst)
        else
            inst.OnEntityReplicated = function(inst)
                container_Widget_change(inst.replica.container)
            end
        end
        -------------------------------------------------------------------------------------------------
    end
----------------------------------------------------------------------------------------------------------------------------------------------------
--- container widget open event 配置界面 可拖动
    local Widget = require "widgets/widget"
    local Image = require "widgets/image"
    local UIAnim = require "widgets/uianim"
    local AnimButton = require "widgets/animbutton"
    local ImageButton = require "widgets/imagebutton"
    local Text = require "widgets/text"
    local function GetHUDLoation()
        local data = TUNING.HUTAO_FNS:Get_ThePlayer_Cross_Archived_Data("cosmic_hat_location")
        if data == nil then
            return 0.5,0.5
        else
            return data.x,data.y
        end
    end
    local function SetHUDLoation(x,y)
        TUNING.HUTAO_FNS:Set_ThePlayer_Cross_Archived_Data("cosmic_hat_location",{x = x,y = y})
    end
    local function container_Widget_opend(inst,root)
        --------------------------------------------------------------------
            --- 按钮
            root.button = root:AddChild(ImageButton("images/ui.xml", "button_small.tex", "button_small_over.tex", "button_small_disabled.tex", nil, nil, {1,1}, {0,0}))
            root.button.image:SetScale(1)
            root.button.text:SetPosition(2,-2)
            root.button:SetPosition(0,130)
            root.button:SetText(STRINGS.ACTIONS.DEPLOY.DEPLOY)
            local move_button = root.button
        --------------------------------------------------------------------
        --- 
            root:SetHAnchor(1) -- 设置原点x坐标位置，0、1、2分别对应屏幕中、左、右
            root:SetVAnchor(2) -- 设置原点y坐标位置，0、1、2分别对应屏幕中、上、下
            root:SetPosition(1000,500) -- 设置原点位置
        --------------------------------------------------------------------
        --- 启动坐标跟随缩放循环任务，缩放的时候去到指定位置。官方好像没预留这类API，或者暂时找不到方法
            function root:LocationScaleFix()
                if self.x_percent and not self.__mouse_holding  then
                    local scrnw, scrnh = TheSim:GetScreenSize()
                    if self.____last_scrnh ~= scrnh then
                        local tarX = self.x_percent * scrnw
                        local tarY = self.y_percent * scrnh
                        self:SetPosition(tarX,tarY)
                    end
                    self.____last_scrnh = scrnh
                end
            end            
            root.x_percent,root.y_percent = GetHUDLoation()
            root:LocationScaleFix()
            root.inst:DoPeriodicTask(2,function()
                root:LocationScaleFix()
            end)
        --------------------------------------------------------------------
        ---- 鼠标拖动
            local old_OnMouseButton = move_button.OnMouseButton
            move_button.OnMouseButton = function(self,button, down, x, y)
                if down and button == MOUSEBUTTON_LEFT then
                    if not root.__mouse_holding  then
                        root.__mouse_holding = true      --- 上锁
                            --------- 添加鼠标移动监听任务
                            root.___follow_mouse_event = TheInput:AddMoveHandler(function(x, y)  
                                root:SetPosition(x,y,0)
                            end)
                            --------- 添加鼠标按钮监听
                            root.___mouse_button_up_event = TheInput:AddMouseButtonHandler(function(button, down, x, y) 
                                if button == MOUSEBUTTON_LEFT and down == false then    ---- 左键被抬起来了
                                    root.___mouse_button_up_event:Remove()       ---- 清掉监听
                                    root.___mouse_button_up_event = nil

                                    root.___follow_mouse_event:Remove()          ---- 清掉监听
                                    root.___follow_mouse_event = nil

                                    root:SetPosition(x,y,0)         ---- 设置坐标
                                    root.__mouse_holding = false    ---- 解锁

                                    local scrnw, scrnh = TheSim:GetScreenSize()
                                    root.x_percent = x/scrnw
                                    root.y_percent = y/scrnh
                                    SetHUDLoation(root.x_percent,root.y_percent)

                                end
                            end)
                    end

                end
                return old_OnMouseButton(self,button, down, x, y)
            end
        --------------------------------------------------------------------
        --- 数值更新
            root.bganim:SetScale(1,1.1)
            root.bganim:SetPosition(0,-15)            
            local bad_luck_value = root.button:AddChild(Text(CODEFONT,40,"000.7",{ 150/255 , 150/255 ,150/255 , 1}))
            bad_luck_value:SetPosition(0,-335)
            local update_value = function()
                local value = inst.replica.hutao_com_cosmic_hat_sys_for_item and inst.replica.hutao_com_cosmic_hat_sys_for_item:GetCurrent()
                --- 使用format 强制保留小数点一位
                local value_str = string.format("%.1f",value)
                bad_luck_value:SetString(value_str)
            end
            root.inst:ListenForEvent("bad_luck_value_update",update_value,inst)
            update_value()
        --------------------------------------------------------------------
    end
----------------------------------------------------------------------------------------------------------------------------------------------------
--- stacksizechange event 用来处理可叠堆的物品 数量变化
    local function item_stacksizechange(item,_table)
        local owner = item.components.inventoryitem.owner
        if owner then
            owner:PushEvent("item_stack_update",item)
        end
    end
----------------------------------------------------------------------------------------------------------------------------------------------------
return function(inst)
    inst:ListenForEvent("hutao_event.container_widget_open",container_Widget_opend)
    add_container_before_not_ismastersim_return(inst)
    if not TheWorld.ismastersim then
        return
    end
    inst:ListenForEvent("itemget",function(inst,_table)
        local item = _table.item
        -- print("++ cosmic hat got item",item)
        if item then
            inst:ListenForEvent("stacksizechange",item_stacksizechange,item)
        end
        inst:DoTaskInTime(0.1,function()
            inst:PushEvent("hat_got_item",{
                item = item,
                owner = inst.components.inventoryitem.owner,
            }) --- 叠堆物品和新物品使用同一事件
        end)
    end)
    inst:ListenForEvent("itemlose",function(inst,_table)
        local item = _table.prev_item
        -- print("++ cosmic hat lost item",item)
        if item then
            inst:RemoveEventCallback("stacksizechange",item_stacksizechange,item)
        end
        inst:PushEvent("hat_lost_item",{
            item = item,
            owner = inst.components.inventoryitem.owner,
        })
    end)
    inst:ListenForEvent("item_stack_update",function(inst,item)
        -- print("++ cosmic hat item_stack_update",item)
        inst:PushEvent("hat_got_item",{ 
            item = item,
            owner = inst.components.inventoryitem.owner
        }) --- 叠堆物品和新物品使用同一事件
    end)
    --- 穿脱的时候刷一下。
    inst:ListenForEvent("equipped",function(inst,_table)
        inst:DoTaskInTime(0.1,function()
            local owner = _table and _table.owner or inst.components.inventoryitem.owner
            for k, item in pairs(inst.components.container.slots) do
                inst:PushEvent("hat_got_item",{
                    item = item,
                    owner = owner,
                }) --- 叠堆物品和新物品使用同一事件
            end
            if not inst.on_equip_dont_open then --- 暂时留个外部接口
                inst.components.container:Open(owner)
            end
        end)
    end)
    inst:ListenForEvent("unequipped",function(inst,_table)
        inst:DoTaskInTime(0.1,function()
            for k, item in pairs(inst.components.container.slots) do
                inst:PushEvent("hat_lost_item",{
                        item = item,
                        owner = _table and _table.owner
                }) --- 叠堆物品和新物品使用同一事件
            end
        end)
        inst.components.container:Close()
    end)
    
end